package Registration;


import java.io.RandomAccessFile;
import java.sql.ResultSet;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Addrate 
{
	final String FILENAME="D:\\Register\\Item\\ItemReport.csv";
	final String OUTPUTFILENAME="D:\\Register\\Item\\debugrate.csv";
	GetIdName gid;
	DBManager database;
	String MRP="mrp";
	String SELL="sell";
	String BUY="buy";
	
	public Addrate() 
	{
		database = new DBManager();
		database.getConnect();
		gid = new  GetIdName(database);
		MRP = gid.getId(MRP);
		BUY = gid.getId(BUY);
		SELL = gid.getId(SELL);
	}
	
	public void AddRate()
	{
		try 
		{	
			RandomAccessFile raf = new RandomAccessFile(FILENAME,"r");
			RandomAccessFile raf1 = new  RandomAccessFile(OUTPUTFILENAME,"rws");
			raf1.setLength(0);
			String line=raf.readLine();
			String splitline[] = line.split("\t");
			int indexofitemcode=-1;
			for(int i=0;i<splitline.length;i++)
			{
				if(splitline[i].equals("Itemcode"))
				{
					indexofitemcode = i;
				}
			}
			line = line + "\t" + "MRP" + "\t" + "SELL" + "\t" + "BUY";
			raf1.writeBytes(line+"\n");
			double mrp,sell,buy;
			mrp=sell=buy=0;
			while((line=raf.readLine())!=null)
			{
				try 
				{
					mrp=sell=buy=0;
					String split[] = line.split("\t");
					String itemcode = split[indexofitemcode];
					itemcode = gid.getId(itemcode);
					String query="select * from rate_master where item=";
					query = query + itemcode;
					
					ResultSet rs;
					String rate;
					try 
					{
						rs = database.getSelect(query + " and BuySell="+MRP);
						rs.next();
						rate = rs.getString("rate");
						mrp = Double.parseDouble(rate);
					}
					catch (Exception e) 
					{
						mrp=0;
						e.printStackTrace();
					}
					
					//line = line + "\t" + rate;
					try 
					{
						rs= database.getSelect(query + " and BuySell="+SELL);
						rs.next();
						rate = rs.getString("rate");
						sell =  Double.parseDouble(rate);
					}
					catch (Exception e) 
					{
						sell=0;
						e.printStackTrace();
					}
					
					//line = line + "\t" + rate;
					try {
						rs= database.getSelect(query + " and BuySell="+BUY);
						rs.next();
						rate = rs.getString("rate");
						buy =  Double.parseDouble(rate);
					} 
					catch (Exception e) 
					{
						buy=0;
						e.printStackTrace();
					}
					//line = line + "\t" + rate;
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
				finally
				{	
					raf1.writeBytes(line+"\t"+mrp+"\t"+sell+"\t"+buy+"\n");
				}
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			
		} 
	}
	public static void main(String[] args) 
	{
		Addrate rate  = new Addrate();
		rate.AddRate();
	}
}
